<template>
  <div>
    <el-form :model="noticeForm" :rules="rules" ref="noticeForm" label-width="100px" style="width:460px">
      <el-form-item label="发送范围：" prop="marketId">
        <el-select v-model="noticeForm.marketId" placeholder="请选择市场">
          <el-option v-for="(item,index) in store.marketOptions" :key="item.marketId" :label="item.marketName" :value="item.marketId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公告状态：">
        <el-select v-model="noticeForm.noticeState">
          <el-option v-for="(item,index) in noticeStateList" :key="item.value" :label="item.name" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否置顶：" >
        <el-radio-group v-model="noticeForm.noticeTop">
          <el-radio-button :label="1">是</el-radio-button>
          <el-radio-button :label="0">否</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="公告标题：" prop="noticeTitle">
        <el-input clearable v-model="noticeForm.noticeTitle" placeholder="公告标题"></el-input>
      </el-form-item>
      <el-form-item label="公告内容：" prop="noticeContent">
        <el-input type="textarea"  :autosize="{ minRows: 2, maxRows: 4}"  v-model="noticeForm.noticeContent" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item  label="有效日期："  prop="noticeDate">
        <el-date-picker
          v-model="noticeDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions2"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('noticeForm')">{{buttonName}}</el-button>
        <el-button @click="turnToList">返回列表</el-button>
        <el-button @click="resetForm('noticeForm')" v-if="!noticeId">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>                                                                                               
<script>

  import func from '@/assets/js/func.js'
  export default {
    data() {
      function dateh (date) {
        let _date = date && (new Date(date)) || new Date()
        return [_date, new Date(Date.parse(_date) + (31536000))]
      }
      return {
        num:0,
        buttonName:'',
        noticeId: this.$route.params.id,
        noticeStateList:[
          {
            name:'有效',
            value: 1
          },
          {
            name:'无效',
            value: 0
          },
        ],
        noticeDate: dateh(),
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        noticeForm:{
          marketId: '',
          noticeState: 1,
          noticeTitle:'',
          noticeTop: 0,
          noticeContent:'',
          noticeStartTime: '',
          noticeEndTime:''
        },
        store:{
          marketOptions:[],
          params:{
            pageSize:10,
            pageIndex:1,
            marketId:this.$marketId,
          },
          isbool:true,
        },
        rules: {
          noticeTitle:[
            { required: true, message: '请输入公告标题', trigger: 'blur' },
            { max: 20, message: '最多20个字符', trigger: 'blur' }
          ],
          noticeDate:[
            { required: true, message: '请选择开始时间', trigger: 'blur' },
          ]
        }
      };
    },
    watch:{
      '$route'(){
        if (!this.$route.params.id){
          this.resetForm('noticeForm')
          this.buttonName = '立即创建'
        }
      },

    },

    created(){
      this.$store.commit('getMarketOptions',this.store)
    },
    methods: {
      getData(){
        this.$axios.get(this.$api.getNoticeInfo,
          { params: {noticeId: this.noticeId }}).then((res) => {
          this.noticeForm = res.data.result.notice;
          var arr = [this.filterForMat(res.data.result.notice.noticeStartTime),this.filterForMat(res.data.result.notice.noticeEndTime)]
          this.noticeDate = arr;
          console.log(this.noticeDate)
          if (res.data.result.marketNum == 1){
            this.noticeForm.marketId = "1"
          }else{
            this.noticeForm.marketId = ""
          }
          delete  this.noticeForm.noticeCreateTime
          delete  this.noticeForm.noticeUpdateTime

        })
      },
      turnToList(){
        this.$router.push('/notice/noticeList')
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      filterForMat(value){
        Date.prototype.toLocaleString = function() {
          return this.getFullYear() + "-" + ((this.getMonth()+1 >= 1 && this.getMonth()+1 <= 9) ? "0" + (this.getMonth()+1):this.getMonth()+1) + "-" +((this.getDate() >= 1 && this.getDate() <= 9) ? "0" + this.getDate():this.getDate())
        };
        var unixTimestamp = new Date(value) ;
        return unixTimestamp.toLocaleString();
      },
      onSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if(valid){
            this.noticeForm.noticeStartTime = func.handleDate('yyyy-MM-dd', this.noticeDate[0])
            this.noticeForm.noticeEndTime = func.handleDate('yyyy-MM-dd', this.noticeDate[1])
            var requestParam = this.noticeForm
            var formData = new FormData();
            for(let i in requestParam){
              formData.append(i,requestParam[i])
            }
            this.$axios({
              method: 'post',
              url: this.$api.insertOrUpdateNotice,
              data: formData
            }).then((res) => {
              if (res.data.code == 1){
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
                this.$router.push('/notice/noticeList')
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
                this.$router.push('/notice/noticeForm')
              }
            })
          }else{
            console.log('提交有问题请查看');
            return false;
          }
        });
      },
    },
    activated() {
      this.noticeId = this.$route.params.id;
      if (this.noticeId != null){
        this.getData();
        this.buttonName = "立即更新"
      }else{
        this.buttonName = "立即创建"
      }
    },
    deactivated() {

    }
  }
</script>
